export default {
	// 为当前模块开启命名空间
	namespaced: true,
	state: () => {
		return {
			//{ goods_id ,goods_name ,goods_price ,goods_count ,goods_small_logo ,goods_state}
			cart: JSON.parse(uni.getStorageSync('cart') || '[]')
		}
	},
	mutations: {
		// 添加到购物车
		addToCart(state, goodsInfo) {
			const res = state.cart.find(item => item.goods_id === goodsInfo.goods_id)
			if (!res) {
				state.cart.push(goodsInfo)
			} else {
				res.goods_count++
			}
			// 数据持久化
			uni.setStorageSync('cart', JSON.stringify(state.cart))
			// this.commit('my_cart/saveStorage')
		},
		// 更新数据
		updataCart(state, newState) {
			state.cart = newState
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		// 修改所有商品选中状态
		updataCartState(state, newState) {
			state.cart.forEach(item => item.goods_state = newState)
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	getters: {
		// 计算总数
		total(state) {
			let c = 0
			// 循环统计商品的数量，累加到变量 c 中
			state.cart.forEach(item => c += item.goods_count)
			return c
		},
		// 选中商品
		checkedGoods(state) {
			const arr = state.cart.filter(item => item.goods_state)
			let count = 0
			let money = 0
			arr.forEach(item=>{
				count += item.goods_count
				money += item.goods_count * item.goods_price
			})
			return { count,money }
		}
	}
}
